package com.mybook.app.controller;

import com.mybook.app.core.BaseResponse;
import com.mybook.app.response.FileUpload;
import com.mybook.app.service.FileUtilsService;
import com.mybook.app.utils.Logger;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/***
 *
 *文件上传类
 *
 */

@RestController
@RequestMapping("/file")
public class FileUtilsController {
    @Autowired
    private FileUtilsService fileUtilsService;

    /**
     * 多图片上传
     *
     * @param
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public BaseResponse<List<FileUpload>> upload(HttpServletRequest httpServletRequest) {
        Logger.info(this, "文件上传 :");
        return new BaseResponse(fileUtilsService.upload(httpServletRequest));
    }


    @PostMapping("/upload/multipart")
    public String uploadMultipartFile(@RequestParam("file") MultipartFile multipartFile) {
        Logger.info(this, "文件上传 :" + multipartFile.getSize());
        FileUpload fileUpload = fileUtilsService.uploadMultipartFile(multipartFile);
        return fileUpload.getFileUrl();
    }

    /**
     * 多图片上传
     *
     * @param
     * @param
     * @return
     * @throws IOException
     */
    @PostMapping("/http/upload")
    public void httpUpload(HttpServletRequest request) {/*
        DefaultMultipartHttpServletRequest defaultMultipartHttpServletRequest = (DefaultMultipartHttpServletRequest) request;
        Map<String, MultipartFile> map = defaultMultipartHttpServletRequest.getFileMap();
        Logger.info(this, "文件上传 :" + map.size());
        List<FileUpload> fileUploadResponses = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> multipartFile : map.entrySet()) {
            Logger.info(this, "文件名称：" + multipartFile.getKey() + "文件大小 ：" + multipartFile.getValue().getSize());
            String path = fileUtilsService.upload(multipartFile.getValue());
            FileUpload fileUploadResponse = new FileUpload();
            fileUploadResponse.setFileUrl(path);
            fileUploadResponse.setUpFileTime(new Date());
            String[] paths = path.split("/");
            fileUploadResponse.setFileName(paths[paths.length - 1]);
            fileUploadResponses.add(fileUploadResponse);
        }
        return new BaseResponse(fileUploadResponses);
    */
    }
}